package ru.spbu.math.android.cbrf.charts;

import java.util.Calendar;
import java.util.GregorianCalendar;

import math.spbu.ru.historycharts.IDataProvider;
import math.spbu.ru.historycharts.renderer.XYMultipleSeriesRenderer;
import ru.spbu.math.android.cbrf.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;

/**
 * @author Nikita
 */
public class DateDialog extends Dialog {

	private AlertDialog invalidDateAlert;
	private Calendar start;
	private Calendar end;

	public DateDialog(Context context, final IDataProvider provider) {
		super(context);
		setContentView(R.layout.date_dialog);

		setTitle(getContext().getResources().getString(R.string.DataPicker));
		final DatePicker startDatePicker = (DatePicker) findViewById(R.id.DatePickerStart);
		final DatePicker endDatePicker = (DatePicker) findViewById(R.id.DatePickerEnd);
		Button applyButton = (Button) findViewById(R.id.ApplyButton);

		XYMultipleSeriesRenderer renderer = provider.getRenderer();

		start = new GregorianCalendar();
		start.setTimeInMillis((long) renderer.getXAxisMin());
		end = new GregorianCalendar();
		end.setTimeInMillis((long) renderer.getXAxisMax());

		startDatePicker.updateDate(start.get(Calendar.YEAR),
				start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH));
		endDatePicker.updateDate(end.get(Calendar.YEAR),
				end.get(Calendar.MONTH), end.get(Calendar.DAY_OF_MONTH));

		AlertDialog.Builder InvalidDataBilder = new AlertDialog.Builder(
				this.getContext());
		InvalidDataBilder.setMessage("Invalid date range");
		InvalidDataBilder.setCancelable(false);
		InvalidDataBilder.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						invalidDateAlert.dismiss();
					}
				});

		invalidDateAlert = InvalidDataBilder.create();

		applyButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				GregorianCalendar today = new GregorianCalendar();
				start = new GregorianCalendar(startDatePicker.getYear(),
						startDatePicker.getMonth(), startDatePicker
								.getDayOfMonth());
				end = new GregorianCalendar(endDatePicker.getYear(),
						endDatePicker.getMonth(), endDatePicker.getDayOfMonth());
				if (end.compareTo(start) > 0 && end.compareTo(today) < 0) {
					XYMultipleSeriesRenderer renderer = provider.getRenderer();
					renderer.setXAxisMin(start.getTimeInMillis());
					renderer.setXAxisMax(end.getTimeInMillis());
					renderer.updateRange(0);
					ChartsActivity.repaintView();
					DateDialog.this.hide();
				} else
					invalidDateAlert.show();
			}
		});
	}
}
